package com.lcz.manage.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

    /** 全局数组 */
    private static final String[] STR_DIGITS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /** MD5加密算法 */
    private static final String ALGORITHM_MD5 = "MD5";

    /**
     * @param str str
     * @return String
     */
    public static String getMd5Code(String str) {
        String resultString;
        try {
            MessageDigest md = MessageDigest.getInstance(ALGORITHM_MD5);
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(str.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            throw new IllegalArgumentException("不存在的加密算法：" + ALGORITHM_MD5);
        }
        return resultString;
    }

    /**
     * 转换字节数组为16进制字串
     *
     * @param byteArray byte数组
     * @return 16进制字串
     */
    private static String byteToString(byte[] byteArray) {
        StringBuilder sb = new StringBuilder();
        for (byte bByte : byteArray) {
            sb.append(byteToArrayString(bByte));
        }
        return sb.toString();
    }

    /**
     * 把byte转为String， 返回形式为数字跟字符串
     *
     * @param bByte byte
     * @return 字符串
     */
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return STR_DIGITS[iD1] + STR_DIGITS[iD2];
    }
}
